package com.touchfired.common.core.listener.impl;

import com.alibaba.fastjson.JSONObject;
import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.ChatEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.utils.DateUtil;
import io.netty.channel.Channel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 客户端连接监听器
 *
 * @author 幸佳俊
 */
@Component
public class ChatListener extends BaseListener<ChatEvent> {

    private final static String SPEAKER = "speaker";
    private final static String CONTENT = "content";
    private final static String DATE = "date";

    @Override
    public void onEvent(ChatEvent event, Callback callback) {
        String content = event.getContent();
        ClientInfo clientInfo = event.getClientInfo();
        List<ClientInfo> clientInfos = event.getClientInfos();
        if (StringUtils.isNotBlank(content) && CollectionUtils.isNotEmpty(clientInfos) && clientInfo != null) {
            JSONObject chatMap = new JSONObject();
            chatMap.put(SPEAKER, clientInfo);
            chatMap.put(CONTENT, content);
            chatMap.put(DATE, DateUtil.nowDateString());

            clientInfos.forEach(client -> {
                Channel channel = client.getChannel();
                if (channel != null) {
                    channel.writeAndFlush(chatMap.toJSONString());
                }
            });
        }
    }
}
